package com.itheima.sh.controller;

import com.itheima.sh.pojo.User;
import com.itheima.sh.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/findAll")
    public List<User> findAll() {
        return userService.findAll();

    }

    //查
    @GetMapping("/{id}")
    public User findUser(@PathVariable("id") Integer id) {
        return this.userService.findUser(id);
    }

    //增
    @PostMapping(produces = "application/json;charset=utf-8")
    public String addUser(@RequestBody User user) {
        this.userService.addUser(user);
        return "增加成功";
    }

    //改
    @PutMapping(value = "/{id}", produces = "application/json;charset=utf-8")
    public String updateUser(@PathVariable("id") Integer id, @RequestBody User user) {
        this.userService.updateUser(id, user);
        return "修改成功";
    }

    @DeleteMapping(value = "/{id}", produces = "application/json;charset=utf-8")
    public String deleteUser(@PathVariable("id") Integer id) {
        this.userService.deleteUser(id);
        return "删除成功";
    }

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }
}
